<?php
/**
 * GioCMS
 * 
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2 
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@ninhgio.com so we can send you a copy immediately.
 * 
 * @copyright	Copyright (c) 2010-2011 GioCMS (http://cms.ninhgio.com)
 * @license		http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @author		NinhGio - ninhgio@gmail.com
 * @since		1.0
 */

class Modules_Core_Services_Widget
{
	public static function add($widget)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$widgetDao = new Modules_Core_Models_Mysql_Widget();
		$widgetDao->setConnection($conn);
		return $widgetDao->add($widget);
	} 
	
	public static function delete($widgetId, $moduleId = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$widgetDao = new Modules_Core_Models_Mysql_Widget();
		$widgetDao->setConnection($conn);
		return $widgetDao->delete($widgetId, $moduleId = null);
	}
	
	public static function dbWidgets($module, $all = false)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$widgetDao = new Modules_Core_Models_Mysql_Widget();
		$widgetDao->setConnection($conn);
		return $widgetDao->dbWidgets($module, $all);
	}
	
	public static function dbWidgetsToolbox($module = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$widgetDao = new Modules_Core_Models_Mysql_Widget();
		$widgetDao->setConnection($conn);
		return $widgetDao->dbWidgetsToolbox($module);
	}
	
	public static function getById($widgetId, $moduleId = null)
	{
		$conn		= Gio_Db_Connection::getConnection();
		$widgetDao = new Modules_Core_Models_Mysql_Widget();
		$widgetDao->setConnection($conn);
		return $widgetDao->getById($widgetId, $moduleId);
	} 
	
	public static function load($module, $name, $action, $params = array(), $cacheEnable = false, $cacheTimeout = 0)
	{
		$configs = Gio_Core_Config_Xml::getConfig('web');
		$widgetContent = Gio_Core_Widget::getIntance()
								->setTemplate($configs->template)
								->setModuleName($module)
								->setWidgetName($name)
								->setActionName($action)
								->setCacheEnable($cacheEnable)
								->setCacheTimeout($cacheTimeout)
								->setParams($params)
								->dispatch();
		
		$view = Gio_Core_View::getInstance();						
		$return = array(
			'title'		=> '',
			'cssFiles'	=> array(), 
			'jsFiles'   => array(),
			'jsScripts' => array(),
			'content' 	=> '',
		);
		$search  = array(
						'{APP_WEB_URL}', 
						'{APP_STATIC_SERVER}',
						'{WIDGET_URL}',
					);
		$replace = array(
						$view->APP_WEB_URL, 
						$view->APP_STATIC_SERVER,
						$view->APP_STATIC_SERVER . '/modules/' . strtolower($module) . '/widgets/' . strtolower($name),
					);

		if ($action != 'config') {			
			/**
			 * Gets widget resources that are defined in widget information file
			 */
			$file = ROOT_DIR . DS . 'modules' . DS . strtolower($module) . DS . 'widgets' . DS . strtolower($name) . DS . 'about.xml';
			if (file_exists($file)) {
				$config = @simplexml_load_file($file);
				if (($resources = $config->resources)) {
					if ($resources = $resources->resource) {
						foreach ($resources as $resource) {
							$attr = $resource->attributes();
							
							switch ((string) $attr['type']) {
								case 'css':
									$return['cssFiles'][] = str_replace($search, $replace, (string) $attr['src']);
									break;
								case 'javascript':
									$return['jsFiles'][]  = str_replace($search, $replace, (string) $attr['src']);
									break;
							}
						}
					}
				}
			}	
		}					
		
		$return['content'] = $widgetContent;
		$pattern = '/<script[^>]*>(.*)<\/script>$/is';
		if (preg_match_all($pattern, $widgetContent, $matches)) {
			$return['jsScripts'] = $matches[1]; 
			$return['content'] = str_replace($matches[1], '', $widgetContent);
		}
		return $return;
	}
	
	public static function getWidgets($module, $frontend = true) 
	{
		$ret = array();
		$widgetsDir = MOD_DIR . DS . $module . DS . 'widgets';
		if (!file_exists($widgetsDir)) {
			return $ret;
		}
		$widgetsIterator = new DirectoryIterator($widgetsDir);
		foreach ($widgetsIterator as $widget) {
			if ($widget->isDot()) {
				continue;
			}
			$widgetName = $widget->getFilename();
			if (('CVS' == $widgetName) || ('.svn' == strtolower($widgetName)) 
					|| ('index.html' == $widgetName)
					|| ('.htaccess' == $widgetName)) {
                continue;
            }
            /**
             * Widget information
             */
            $xmlFile = $widgetsDir . DS . $widgetName . DS . 'about.xml';
            if (file_exists($xmlFile)) {
	            $xmlData = @simplexml_load_file($xmlFile);
	            if (!isset($xmlData->frontend) || (bool)$xmlData->frontend == false) {
		            $data = array(
		            	'widget_id'			=> (string)$xmlData->name,
		            	'module_id'			=> (string)$xmlData->module,
		            	'thumbnail'			=> (string)$xmlData->thumbnail,
		            	'author'			=> (string)$xmlData->author,
		            	'email'  			=> (string)$xmlData->email,
		            	'title'				=> (string)$xmlData->title->attributes()->langKey,
		            	'description'		=> (string)$xmlData->description->attributes()->langKey
		            );
		            $ret[] = $data;
	            }
            }
		}
		return $ret;
	}
}